package com.teragadgets.android.comic.datamodel;

import java.util.Vector;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.util.Log;

public class WebComicDatabase {

	/*******************************************************
	 * These constants refer to the fields in the database. _id is Android's
	 * naming convention for ID fields. Our database has 3 fields, so we have 3
	 * constants.
	 ********************************************************/

	public static final String KEY_WEBSITE_NAME = "website_name";
	public static final String KEY_BASE_URL = "base_url";
	public static final String KEY_LOGO_URL = "logo_url";
	public static final String KEY_NUMBER_OF_COMICS = "number_of_comics";
	public static final String KEY_LAST_READ = "last_read";
	public static final String KEY_ORDER = "comic_order";
	public static final String KEY_ROWID = "_id";
	public static final String[] allVals = new String[] { KEY_ROWID,
			KEY_WEBSITE_NAME, KEY_BASE_URL, KEY_LOGO_URL, KEY_NUMBER_OF_COMICS,
			KEY_LAST_READ, KEY_ORDER };

	private DatabaseHelper dbHelper;
	private SQLiteDatabase db;

	private Context mCtx = null;

	/*******************************************************
	 * Some other constants related to our database's information. They should
	 * be self explanatory
	 ********************************************************/
	private static final String DATABASE_NAME = "comic_db";
	private static final String DATABASE_TABLE = "comics";
	private static final int DATABASE_VERSION = 8;
	private static final String DATABASE_CREATE = "create table comics ( "
			+ "_id integer primary key autoincrement, "
			+ "website_name varchar(60), " + "base_url varchar(60), "
			+ "logo_url varchar(130), " + "number_of_comics tinyint, "
			+ "last_read tinyint, " + "comic_order tinyint" + ");";

	/********************************************************
	 * Think of this as a driver for your database interaction. You can just
	 * copy and paste this part in all your database interaction classes.
	 *********************************************************/
	private static class DatabaseHelper extends SQLiteOpenHelper {
		DatabaseHelper(Context ctx) {
			super(ctx, DATABASE_NAME, null, DATABASE_VERSION);
		}

		@Override
		public void onCreate(SQLiteDatabase db) {
			db.execSQL(DATABASE_CREATE);
		}

		@Override
		public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
			db.execSQL("DROP TABLE IF EXISTS " + DATABASE_TABLE);
			onCreate(db);
		}
	}

	/** Constructor */
	private WebComicDatabase(Context ctx) {
		mCtx = ctx;
		dbHelper = new DatabaseHelper(mCtx);
		db = dbHelper.getWritableDatabase();
	}

	/********************************************************
	 * This opens a connection to the database but if something goes wrong, it
	 * will throw an exception.
	 ********************************************************/
	public static WebComicDatabase open(Context mCtx) throws SQLException {
		return new WebComicDatabase(mCtx);
	}

	/** Closes a database connection */
	public void close() {
		dbHelper.close();
	}

	public Vector<WebComic> fetchAllComics() {
		try {
			Vector<WebComic> comics = new Vector<WebComic>();

			Cursor cursor = db.query(DATABASE_TABLE, allVals, null, null, null,
					null, KEY_WEBSITE_NAME);
			int size = cursor.getCount();
			for (int i = 0; i < size; i++) {
				cursor.moveToNext();
				comics.add(new WebComic(getWebsiteName(cursor),
						getBaseURL(cursor), getLogoURL(cursor),
						getRowID(cursor), getNumberOfComics(cursor),
						getLastRead(cursor), getOrder(cursor)));
			}
			cursor.close();
			return comics;

		} catch (Exception e) {
			Log.e("DBLayer", e.getMessage());
			return null;
		}
	}

	public WebComic fetchComic(String id) {
		try {
			Cursor cursor = db.query(DATABASE_TABLE, allVals, KEY_ROWID + "="
					+ id, null, null, null, KEY_WEBSITE_NAME);
			cursor.moveToFirst();
			WebComic comic = new WebComic(getWebsiteName(cursor),
					getBaseURL(cursor), getLogoURL(cursor), getRowID(cursor),
					getNumberOfComics(cursor), getLastRead(cursor),
					getOrder(cursor));
			cursor.close();
			return comic;
		} catch (Exception e) {
			Log.e("DBLayer", e.getMessage());
			return null;
		}
	}

	public boolean webComicExists(String id) {
		try {
			Cursor cursor = db.query(DATABASE_TABLE,
					new String[] { KEY_ROWID }, KEY_ROWID + "=" + id, null,
					null, null, null);
			boolean result = cursor.getCount() > 0;
			cursor.close();
			return result;
		} catch (Exception e) {
			Log.e("DBLayer", e.getMessage());
			return false;
		}
	}

	public String getAllIDs() {
		try {
			Cursor cursor = db.query(DATABASE_TABLE,
					new String[] { KEY_ROWID }, null, null, null, null, null);
			String allIDs = "";
			while (cursor.moveToNext()) {
				allIDs += getRowID(cursor) + ",";
			}
			cursor.close();
			return allIDs;
		} catch (Exception e) {
			Log.e("DBLayer", e.getMessage());
			return null;
		}
	}

	public long addNewWebComic(String websiteName, String id, String baseUrl,
			String logoUrl, String numberOfComics) {
		ContentValues vals = new ContentValues();
		vals.put(KEY_WEBSITE_NAME, websiteName);
		vals.put(KEY_ROWID, id);
		vals.put(KEY_BASE_URL, baseUrl);
		vals.put(KEY_LOGO_URL, logoUrl);
		vals.put(KEY_NUMBER_OF_COMICS, numberOfComics);
		vals.put(KEY_LAST_READ, -1);
		return db.insert(DATABASE_TABLE, null, vals);
	}

	public boolean updateLastRead(String string, int lastRead) {
		ContentValues vals = new ContentValues();
		vals.put(KEY_LAST_READ, lastRead);
		int success = db.update(DATABASE_TABLE, vals, KEY_ROWID + "=" + string,
				null);
		return success > 0;
	}

	public boolean updateComic(long rowId, String websiteName, String baseUrl,
			String logoUrl, String numberOfComics, int lastRead) {
		ContentValues vals = new ContentValues();
		vals.put(KEY_WEBSITE_NAME, websiteName);
		vals.put(KEY_BASE_URL, baseUrl);
		vals.put(KEY_LOGO_URL, logoUrl);
		vals.put(KEY_NUMBER_OF_COMICS, numberOfComics);
		vals.put(KEY_LAST_READ, lastRead);
		return db.update(DATABASE_TABLE, vals, KEY_ROWID + "=" + rowId, null) > 0;
	}

	public boolean deleteComic(String string) {
		return db.delete(DATABASE_TABLE, KEY_ROWID + "=" + string, null) > 0;
	}

	public boolean deleteAll() {
		return db.delete(DATABASE_TABLE, KEY_ROWID + ">" + -1, null) > 0;
	}

	private String getRowID(Cursor cursor) {
		return cursor.getString(cursor.getColumnIndex(KEY_ROWID));
	}

	private String getWebsiteName(Cursor cursor) {
		return cursor.getString(cursor.getColumnIndex(KEY_WEBSITE_NAME));
	}

	private String getBaseURL(Cursor cursor) {
		return cursor.getString(cursor.getColumnIndex(KEY_BASE_URL));
	}

	private String getLogoURL(Cursor cursor) {
		return cursor.getString(cursor.getColumnIndex(KEY_LOGO_URL));
	}

	private int getNumberOfComics(Cursor cursor) {
		return cursor.getInt(cursor.getColumnIndex(KEY_NUMBER_OF_COMICS));
	}

	private int getLastRead(Cursor cursor) {
		return cursor.getInt(cursor.getColumnIndex(KEY_LAST_READ));
	}

	private int getOrder(Cursor cursor) {
		return cursor.getInt(cursor.getColumnIndex(KEY_ORDER));
	}

	public boolean updateFromAppEngine(WebComic c) {
		ContentValues vals = new ContentValues();
		vals.put(KEY_WEBSITE_NAME, c.getName());
		vals.put(KEY_BASE_URL, c.getURL());
		vals.put(KEY_LOGO_URL, c.getIconURL());
		vals.put(KEY_NUMBER_OF_COMICS, c.getNumberOfComics());
		if (db.update(DATABASE_TABLE, vals, KEY_ROWID + "=" + c.getID(), null) > 0) {
			return true;
		} else {
			vals.put(KEY_ROWID, c.getID());
			vals.put(KEY_LAST_READ, -1);
			vals.put(KEY_ORDER, -1);
			return db.insert(DATABASE_TABLE, null, vals) > 0;
		}
	}

	public boolean updateOrder(String id, int order) {
		ContentValues vals = new ContentValues();
		vals.put(KEY_ORDER, order);
		int success = db.update(DATABASE_TABLE, vals, KEY_ROWID + "=" + id,
				null);
		return success > 0;
	}

}